const Router = require('koa-router');

const Tag = require('../models/tag')

let router = new Router({
  prefix: '/api'
})

// 获取标签
router.get('/tag/get', async(ctx) => {
  const { name } = ctx.request.query
  let filterObj = {}
  name && (filterObj.name = new RegExp(name))
  try {
    const tags = await Tag.find(filterObj).sort({'createTime': -1})
    if (tags) {
      ctx.body = {
        code: 0,
        data: tags
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '查询失败'
      }
    }
  } catch (err) {
    ctx.body = {
      code: -1,
      msg: '服务器异常'
    }
  }
})

// 新增标签
router.post('/tag/add', async(ctx) => {
  const {name} = ctx.request.body
  const tag = await Tag.findOne({name: name})
  if (tag) {
    ctx.body = {
      code: -1,
      msg: '标签已存在'
    }
  } else {
    const newTag = await Tag.create({name, createTime: Math.round(new Date())})
    if (newTag) {
      ctx.body = {
        code: 0,
        msg: `标签"${name}"增加成功`
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '标签增加失败'
      }
    }
  }
})

// 删除标签
router.get('/tag/del', async(ctx) => {
  const {id} = ctx.request.query
  try {
    const del = await Tag.remove({_id: id})
    if (del) {
      ctx.body = {
        code: 0,
        msg: '删除成功'
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '删除失败'
      }
    }
  } catch (err) {
    ctx.body = {
      code: -1,
      msg: '服务器异常'
    }
  }
})

module.exports = router